package com.yxy.http.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.*;

/**
 * Created by zhaolf on 2017/3/24.
 */
public class FileUtility {

    private static Logger logger = LogManager.getLogger("FileUtility");

    /**
    * 取得项目目录地址下的指定目录绝对地址
    */
    public static String getDirectory(final String baseFolder, final String folderName) throws IOException {

        String filePath = getDirectory(baseFolder);
        String path = filePath + File.separator + folderName;

        File directory = new File(path);
        if (!directory.exists()) {
            directory.mkdir();
        }
        return path;
    }

    public static String getDirectory(String folderName) throws IOException {

        File root = new File("");
        String path = root.getCanonicalPath() + File.separator + folderName;

        File directory = new File(path);
        if (!directory.exists()) {
            directory.mkdir();
        }
        return path;
    }


    /**
     * 文件复制到指定位置
     * @param sourceFileName 源文件
     * @param destFileName 复制目标文件
     * @throws IOException
     */
    public static void copyFile(String sourceFileName, String destFileName) throws IOException {
        InputStream fi = null;
        OutputStream fo = null;
        try {
            File sourceFile = new File(sourceFileName);
            File destFile = new File(destFileName);
            if (destFile.exists()) {
                destFile.delete();
            }
            if (sourceFile.exists()) {
                fi = new BufferedInputStream(new FileInputStream(sourceFile));
                fo = new BufferedOutputStream(new FileOutputStream(destFile));

                byte[] buffer = new byte[1024 * 4];
                int index = 0;
                while ((index = fi.read(buffer)) != -1) {
                    fo.write(buffer, 0, index);
                }
            }
        } finally {
            try {
                if (null != fi) {
                    fi.close();
                }
                if (null != fo) {
                    fo.close();
                }
            } catch (IOException e) {
                logger.error("源文件{}复制到{}出错！" + e.getMessage(), sourceFileName, destFileName);
            }
        }
    }

    /**
     * 删除文件
     * @param fileName
     */
    public static void deleteFile(String fileName) {
        File file = new File(fileName);
        if (file.exists()) {
            file.delete();
        }
    }

    /**
     *取得消息体
     * @param fileName
     * @param filter
     * @return  send_receive_messageId
     * @throws IOException
     */
    public static String getFileNameNoSuffix(String fileName, String filter) throws IOException {
        String temp = "";
        File file = new File(fileName);
        if (file.exists() && fileName.toUpperCase().contains(filter)) {
            if (fileName.contains(File.separator)) {
                temp = fileName.substring(fileName.lastIndexOf(File.separator) + 1, fileName.lastIndexOf('.'));
            } else {
                temp = fileName.substring(0, fileName.lastIndexOf('.'));
            }
        }
        return temp;
    }

    /**
     * 读取文件为字节数组
     * @param fileName 文件名
     * @return 字节组
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static byte[] ReadFileToBytes(String fileName) throws IOException {
        byte[] blob = null;
        InputStream fi = null;
        try {
            File file = new File(fileName);
            if (file.exists()) {
                fi = new BufferedInputStream(new FileInputStream(file));

                blob = new byte[fi.available()];
                fi.read(blob);
            }
        } finally {
            try {
                if (null != fi) {
                    fi.close();
                }
            } catch (IOException e) {
                logger.error("读取源文件{}出错，不能生成字节数组！" + e.getMessage(), fileName);
            }
        }
        return blob;
    }

    /**
     * 生成文件
     * @param fileName
     * @param buffer
     * @throws IOException
     */
    public static void SaveBytesToFile(String fileName, byte[] buffer) throws IOException {
        FileOutputStream fos = null;
        try {
            File file = new File(fileName);
            if (file.exists()) {
                file.delete();
            }
            fos = new FileOutputStream(file);
            fos.write(buffer);
        } finally {
            try {
                if (null != fos) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String getFileName(String folder, String fileName) {
        return folder + File.separator + fileName;
    }

    /**
     * 递归删除文件夹内所有文件以及文件夹
     * @param dir
     * @return
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }



}
